package zdream.rockchronicle;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.files.FileHandle;

import java.util.function.BooleanSupplier;

import zdream.control.world.LevelWorld;
import zdream.control.world.MHookStore;
import zdream.control.world.MHookType;
import zdream.control.world.MHooks;
import zdream.rockchronicle.core.graphics.LevelGraphics;
import zdream.rockchronicle.core.input.InputCenter;
import zdream.control.profile.ProfileManager;
import zdream.rockchronicle.core.region.TmxStorage;
import zdream.rockchronicle.core.textures.TextureManager;
import zdream.rockchronicle.utils.FilePathUtil;
import zdream.utils.function.VoidFunction;

/**
 * 游戏主体
 * 
 * @author Zdream
 */
public class RockChronicle {
	public static RockChronicle INSTANCE;

	public static void initFromGame(Game game) {
		initFromGame(game, new Config());
	}

	public static void initFromGame(Game game, Config config) {
		if (INSTANCE == null) {
			INSTANCE = new RockChronicle(game, config);
		}
	}

	RockChronicle(Game game, Config config) {
		this.game = game;
		this.config = config;
		config.projectPath = System.getProperty("user.dir");

		final LevelWorld.LevelWorldSpec description = new LevelWorld.LevelWorldSpec();
		description.graphics = this.graphics = new LevelGraphics(this);
		description.resourcePath = "res/foes";
		levels = new LevelWorld(description);

		storage = new TmxStorage(this);
	}

	// 其它数据
	public int width = 25 * 48;
	public int height = 14 * 48;
	public String version;

	public final Game game;
	public final Config config;

	// Manager
	public InputCenter input;
	public ProfileManager profiles;
	public TextureManager assets;
	public LevelGraphics graphics;
	public LevelWorld levels;
	public TmxStorage storage;

	// 显示组件

	public static long getWorldTime() {
		return INSTANCE.levels.ticker.worldTime;
	}

	public static long getActiveTime() {
		return INSTANCE.levels.ticker.activeTime;
	}

	public MHooks.MHookContext triggerEvent(MHookType type) {
		return levels.triggerEvent(type);
	}

	public BooleanSupplier putSubscriber(VoidFunction listener, MHookType type) {
		return levels.putSubscriber(listener, type);
	}

	public MHookStore.HookHandlerBuilder createSubscriber(MHookType type) {
		return levels.createSubscriber(type);
	}

	// 与引擎相关的
	public void create() {
		input = new InputCenter();
		profiles = new ProfileManager();
		assets = new TextureManager();
		// 初始化
		profiles.init();
		graphics.init();
		input.init();
		storage.init();
	}
	
	public String chineseCharacter() {
		FileHandle f = FilePathUtil.localFiles("res", "conf", "chinese_character.txt");
		String text = f.readString("UTF-8");
		text += "Ｉ";
		return text.replaceAll("\n|\r|\t|\\s*", "");
	}

	/**
	 * 退出游戏
	 */
	public void exit() {
		game.dispose();
		System.exit(0);
	}
}
